package com.example.cardgame

import android.os.Bundle
import android.graphics.Color
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.children
//import androidx.compose.ui.graphics.Color
import cn.edu.sicnu.cardgame.CardMatchingGame
import com.example.cardgame.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {


    lateinit var game:CardMatchingGame

    val cardButtons = mutableListOf<Button>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val contextBinding =ActivityMainBinding.inflate(layoutInflater)
        setContentView(contextBinding.root)
        for (v in contextBinding.gridLayout.children){
            if(v is Button){
                v.setOnClickListener {
                    val index = cardButtons.indexOf(v)
                    game.chooseCardAtIndex(index)
                    updateUI()

                }
                cardButtons.add(v)
            }
        }
        game = CardMatchingGame(cardButtons.count())
        updateUI()

        contextBinding.reset.setOnClickListener{
            game = CardMatchingGame(cardButtons.count())
            updateUI()
        }
    }

    fun updateUI(){
        val binding =ActivityMainBinding.inflate(layoutInflater)
        for(button in cardButtons){
            val index = cardButtons.indexOf(button)
            val card = game.cardAtIndex(index)
            button.isEnabled =!card.isMatched
            if(card.isChosen){
                button.text =card.toString()
                button.setBackgroundColor(Color.WHITE)
            }else{
                button.text="o"
                button.setBackgroundResource(R.drawable.puke)
            }
        }
        binding.score.text = String.format("%s%d","分数:",game.score)
    }
}